package com.baize.baizeapp.test.widget

import android.content.Context
import android.text.InputFilter
import android.text.Spanned
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatEditText
import com.baize.baizeapp.R
import java.util.regex.Pattern

class HSCountSelector @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {


    lateinit var ivDecrease: ImageView
    lateinit var ivAdd: ImageView
    lateinit var etNumber: AppCompatEditText

    var limitMax = 200
        set(value) {
            field = value
            if (getCurrentNum() > limitMax) {
                setCurrentNum(limitMax)
            }
            isEnabled = limitMax > limitMin
        }
    var limitMin = 1
        set(value) {
            field = value
            if (getCurrentNum() < limitMin) {
                setCurrentNum(limitMin)
            }
            isEnabled = limitMin > limitMax
        }

    init {
        val componentView =
            LayoutInflater.from(context).inflate(R.layout.heishi_count_selector, this)
        ivDecrease = componentView.findViewById(R.id.pay_business_decrease)
        etNumber = componentView.findViewById(R.id.pay_business_product_buy_number)
        ivAdd = componentView.findViewById(R.id.pay_business_add)
        ivDecrease.setOnClickListener {
            var currCount = getCurrentNum()
            if ((currCount - 1) < limitMin) {
                return@setOnClickListener
            }
            setCurrentNum(currCount - 1)
        }
        ivAdd.setOnClickListener {
            var currCount = getCurrentNum()
            if ((currCount + 1) > limitMax) {
                return@setOnClickListener
            }
            setCurrentNum(currCount + 1)
        }
        etNumber.filters = arrayOf(NumberScopeLimitFilter())
        etNumber.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) { //失去焦点
                val inputStr = etNumber.text.toString()
                if (TextUtils.isEmpty(inputStr)
                    || (inputStr.toIntOrNull() ?: limitMin) !in limitMin..limitMax
                ) {
                    setCurrentNum(limitMin)
                }
            }
        }
        setCurrentNum(limitMin)
    }

    fun setCurrentNum(num: Int) {
        etNumber.setText(num.toString())
    }

    fun getCurrentNum(): Int {
        val count = etNumber.text.toString().toIntOrNull() ?: limitMin
        return count
    }

    /**
     * 输入数字范围限制
     */
    inner class NumberScopeLimitFilter : InputFilter {

        var mPattern: Pattern = Pattern.compile("(0)*")

        override fun filter(
            source: CharSequence?,
            start: Int,
            end: Int,
            dest: Spanned?,
            dstart: Int,
            dend: Int
        ): CharSequence? {
            val sourceText = source.toString()
            val destText = dest.toString()
            Log.i("yanze_input", "source:${sourceText} start:$start end:$end dest:$destText dstart:$dstart dend:$dend")
            Log.i("yanze_input", "return :${dest?.subSequence(dstart, dend).toString() + sourceText}  ${dest?.subSequence(dstart, dend)}")
            //删除字符
            if (TextUtils.isEmpty(sourceText)) {
                val strArrStr = destText.subSequence(0, dstart).toString()
                val strArrEnd = destText.subSequence(dend,destText.length).toString()
                val numText = (strArrStr + strArrEnd).toIntOrNull() ?: -1
                Log.i("yanze_input","预测删除后数字：${numText}")
                return if (numText !in limitMin..limitMax) {
                    dest?.subSequence(dstart, dend)
                } else ""
            }
            //输入字符
            //1. 首位不能输入0
            if (mPattern.matcher(sourceText).matches() && dstart == 0) {
                return dest?.subSequence(dstart, dend)
            }
            val strArrStr = destText.subSequence(0, dstart).toString()
            val strArrEnd = destText.subSequence(dstart,destText.length).toString()
            val numTextNew = (strArrStr + sourceText + strArrEnd).toIntOrNull() ?: -1
            Log.i("yanze_input","预测输入后数字：${numTextNew}")
            //2. 最终结果数字要比最大值小，否则输入无效
            return if (numTextNew !in limitMin..limitMax) {
                dest?.subSequence(dstart, dend)
            } else {
                dest?.subSequence(dstart, dend).toString() + sourceText
            }
        }
    }

}